<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\CouponDsecModel as StoreCoupon;
use app\api\model\Users;
use think\Request;

class PonintsRedemptionCoupon
{
    /**
     * 积分优惠券列表查询
     * @return \think\Response
     */
    public function index()
    {

        $CouponData = StoreCoupon::select();

        if (empty($CouponData)){
            return json(['code'=>400,'msg'=>'数据不存在，查询失败','data'=>'']);
        }

        return  json(['code'=>200,'msg'=>'查询成功','data'=>$CouponData]);
    }

    /**
     *  用户使用积分兑换优惠券
     * @param Request $request
     */
    public function exchangeCoupon(Request $request)
    {
        // 接前台传来的优惠券id
        $points_id = $request->id;

        // 自定义用户id为1
        $uid = 1;
        // 查询用户表用户拥有的积分
        $PointsUser = Users::where('id',$uid)->find();

        // 查询兑换每个优惠券所需要的积分
        $CouponPoints = StoreCoupon::where('id',$PointsUser)->find();

        // 当用户兑换优惠券时进行积分的加减
        if ($PointsUser['points'] < $CouponPoints['integral']){
            return json(['code'=>4001,'msg'=>'您的积分不足，无法进行兑换','data'=>'']);
        }

        if ($PointsUser['points'] > $CouponPoints['integral']){

            $PointsUser->save( $PointsUser['points'] - $CouponPoints['integral']);

            // 根据当前选择的优惠券id查询出兑换的优惠券
            $coupon = StoreCoupon::where('id',$PointsUser)->find();


            // 把优惠券放到用户额优惠券包内(包含优惠券的信息，已经对应的用户id)
            $userCoupon = SelfCoupon:: create([
                'u_id' => $PointsUser['id'],
                'title' => $CouponPoints['title'],
            ]);
        }

        return json(['code'=>200,'msg'=>'优惠券兑换成功']);
    }
}
